/**
 *	流程模块主Flow条件使用
 *	开发者：雨中磐石
 *	地址：www.rockoa.com
 *	日期：2023-07-22
 */

package com.framework.Flow;




import com.framerock.db.DB;
import com.framerock.baselib.CDate;
import com.framerock.baselib.Jiami;
import com.framerock.baselib.Patter;
import com.framerock.baselib.Rock;
import com.framework.ACore.Model;
import com.framework.Model.ModelReim;
import java.util.ArrayList;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class FlowWhere extends FlowBase {

    /**
     * 查看条件
     * */
    public static int WTYPE_VIEW  = 1;

    /**
     * 普通的条件
     * */
    public static int WTYPE_WHERE  = 0;

    /**
     * 删除的条件
     * */
    public static int WTYPE_DEL  = 3;

    /**
     * 编辑的条件
     * */
    public static int WTYPE_EDIT  = 2;


    private Model whereModel;

    public FlowWhere(Flow flows) {
        super(flows);
        whereModel = Model.get(this.nDb, "flowwhere");
    }

    /**
     * 获取列表页选择卡
     * @param pnum 分组编号
     * */
    public ArrayList<Map<String, String>> getAtypeArr(String pnum)
    {
        ArrayList<Map<String, String>> rows;
        rows = whereModel.getAll("`modeid`="+mFlow.modeid+" AND `pnum`='"+pnum+"' AND `islb`=1 AND `status`=1", "`num`,`name`", "`sort`");
        if(mFlow.isManage()){
            if(rows == null)rows = Rock.getMapList();
            rows.add(Rock.getMap("name=管理,num=managelist"));
        }
        if(mFlow.unitrs != null)
            ModelReim.get(this.nDb).yiduHistory(4, mRequest.USEAID, Integer.parseInt(mFlow.funitid));
        return rows;
    }

    /**
     * 读取条件
     * @param wtype 读取的条件类型0|条件,1|查看条件,2|编辑条件,3|删除条件
     * */
    public Boolean whereAuth(int wtype)
    {
        ArrayList<Map<String, String>> rows = whereModel.getAll("`modeid`="+mFlow.modeid+" AND `wtype`="+wtype+" AND `status`=1");
        Map<String, String> rs;
        String str = "";
        int to;
        if(rows != null)for(int i=0;i<rows.size();i++){
            rs  = rows.get(i);
            str = this.getFlowwheres(rs.get("where"), rs.get("num"));
            if(Rock.isEmpt(str)){
                return true;
            }else{
                to = mFlow.mModel.getCount("`id`="+mFlow.mid+" AND "+str+"");
                if(to>0)return true;
            }
        }
        return null;
    }

    /**
     * 通过编号获取条件
     * @param num 条件编号
     * @param qom 主表别名如a.
     * */
    public String getFlowwhere(String num, String qom)
    {
        String str = "";
        if(num.equals("managelist")){
            str = "1=2";
            if(mFlow.isManage()){
                str = "";
            }
        }else {
            String where = "`modeid`=" + mFlow.modeid + " AND ";
            if (Patter.isnumber(num)) {
                where += "`id` = " + num + "";
            } else {
                where += "`num`='" + num + "'";
            }
            Map<String, String> wrs = whereModel.getOne(where);
            str = this.getFlowwheres(Rock.getMapString(wrs, "where"), num);
        }
        if(!Rock.isEmpt(str))str = str.replace("[A].", qom);
        return str;
    }

    /**
     * 条件处理str为base64的
     * @param str 要解析字符串
     * @param num 条件编号
     * */
    public String getFlowwheres(String str, String num)
    {
        if (!Rock.isEmpt(str)) {
            str = Jiami.base64decode(str);
            str = this.defaultValue(str);
            if (str.equals("1=1")) str = "";
        }
        if (!Rock.isEmpt(str)) str = "( " + str + " )";
        if(!Rock.isEmpt(num)) {
            String ostr = mFlow.mFlowListener.ongetFlowwhere(num);
            if (!Rock.isEmpt(ostr)) {
                if (!Rock.isEmpt(str)) str += " AND ";
                str += ostr;
            }
        }
        return str;
    }

    /**
     * 默认值的处理替换如
     * @param str 变量替换，如{aid}替换为单位用户id
     * */
    public String defaultValue(String str)
    {
        if(str.indexOf("{")==-1 && str.indexOf("}")==-1)return str;
        Pattern p = Pattern.compile("\\{(.*?)\\}");
        Matcher m = p.matcher(str);
        String neirs = "",nval;
        while (m.find()) {
            neirs = m.group();
            nval  = this.defaultValues(neirs);
            str   = str.replace(neirs, nval);
        }
        return str;
    }

    /**
     * 变量替换
     * @param str 变量替换，如{aid}替换为单位用户id
     * */
    private String defaultValues(String str)
    {
        String key = str.substring(1, str.length()-1),arr[],fid,val;
        if(key.equals("aid"))str  = mRequest.USEAID;
        if(key.equals("date"))str = CDate.date();
        if(key.equals("now"))str  = CDate.now();
        if(key.equals("useaname"))str = mRequest.getUserars("name");
        if(key.equals("deptname"))str = mRequest.getUserars("deptname");
        if(key.equals("companyname"))str = mRequest.getCompanyrs("name");
        //{receid,字段}
        if(key.indexOf("receid")==0){
            fid = "receid";
            arr = key.split(",");
            if(arr.length > 1)fid = arr[1];
            str = receidWhere(mRequest.getUserainfo(), fid, key.indexOf("not")<0, "");
            if(Rock.isEmpt(str))str = "1=2";
        }
        //{aidin,字段}
        if(key.indexOf("aidin")==0){
            fid = "aids";
            arr = key.split(",");
            if(arr.length > 1)fid = arr[1];
            str = DB.dbInstr(fid, mRequest.USEAID);
        }
        if(key.indexOf("ars.")==0){
            str = mRequest.getUserars(key.substring(4));
        }
        return str;
    }

    /**
     * receid的条件组合条件
     * @param ars 单位用户信息
     * @param fid 字段
     * @param ebo 为空时需要
     * @param orwhere 其他or的条件
     * */
    public String receidWhere(Map<String, String> ars, String fid, Boolean ebo, String orwhere)
    {
        if(ars == null)return  "";
        String deptpath = mFlow.modelUsera.dept().useraPath(ars);
        String str      = "",val,vstr = orwhere;
        String arr[]    = deptpath.split(",");
        if(!Rock.isEmpt(vstr))str = vstr;
        if(ebo){
            if(!Rock.isEmpt(str))str += " OR ";
            str  += ""+fid+" = ''";
        }
        for(int i=0; i<arr.length; i++){
            val = arr[i];
            if(!Rock.isEmpt(val)){
                if(!Rock.isEmpt(str))str += " OR ";
                str += DB.dbInstr(fid, val);
            }
        }
        if(!Rock.isEmpt(str))str = "("+str+")";
        return str;
    }
}
